package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    @Override
    @Transactional//涉及多表操作，开启事务
    public void insert(DishDTO dto) {
//        1.拷贝传入的数据到dish表中
        Dish dish = new Dish();

        BeanUtils.copyProperties(dto, dish);

//        2.调用DishMapper的接口，新增菜品

        dishMapper.insert(dish);

        //DishDTO中没有dish的主键id，所以需要获取到dish的id用于菜品表中的dishld的逻辑外键相连接
        log.info("dish id={}", dish.getId());

        List<DishFlavor> dishFlavorList = dto.getFlavors();

        dishFlavorList.forEach(dishFlavor ->
                dishFlavor.setDishId(dish.getId())          //将遍历到的dish主键id赋值给dishFLavor表中的dishId，可能存在多种口味，所以用foreach
        );


//        3.调用DishFlavorMapper接口，新增菜品口味
        dishFlavorMapper.insertBatch(dishFlavorList);


    }

    /*
     * 菜品分页查询
     * */
    @Override
    public PageResult selectPage(DishPageQueryDTO dto) {
//        1.分页插件
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

//        2.调用mapper强转Page,查询出来的是个集合

        Page<DishVO> p = dishMapper.list(dto);


//        3.返回Pageresult对象
        return new PageResult(p.getTotal(), p.getResult());


    }

    /*
     * 批量删除菜品
     * */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //删除不能联表删除
//        1.起售中的菜品不能删除
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

//        2.被套餐关联的菜品不能删除
        Integer count = setmealDishMapper.selectCount(ids);
        ids.forEach(id -> {
            if (count > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });


//        增强for循环批量删除
        for (Long id : ids) {
//            批量删除菜品
            dishMapper.delete(id);

//            关联的口味数据也需要删除掉

            dishFlavorMapper.delete(id);
        }

////        3.可以一次删除一个菜品，也可以批量删除菜品
//        dishMapper.deleteBatch(ids);
//
//
////        4.删除菜品后，关联的口味数据也需要删除掉
//
//        dishFlavorMapper.deleteBatch(ids);
//


    }


    /*
     * 根据ID修改回显菜品
     * */
    @Override
    public DishVO selectById(Long id) {
        DishVO dishVO = new DishVO();
//        1.根据id查询菜品表
        Dish dish = dishMapper.selectById(id);
//将获取的菜品信息copy到dishDTO中
        BeanUtils.copyProperties(dish, dishVO);
//2.根据id查询菜品口味表
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectById(id);

        dishVO.setFlavors(dishFlavorList);


        return dishVO;
    }

    /*
     * 修改菜品
     * */
    @Override
    @Transactional  //设计多张表，开启事务
    public void update(DishDTO dto) {
//        1.修改菜品表  在改动表数据的时候，传入表对象，而不是dto
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.update(dish);

//        2.修改菜品口味表,由于菜品口味设计增删改操作，所以先删除后修改
        dishFlavorMapper.delete(dto.getId());


        List<DishFlavor> dishFlavorList = dto.getFlavors();

        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });

        }
        dishFlavorMapper.insertBatch(dishFlavorList);
    }

    /*
     * 菜品起售、停售
     * */
    @Override
    @Transactional
    public void startorclose(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        //如果是停售操作，还要将包含当前菜品的套餐也停售
        if (status == StatusConstant.DISABLE) {
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /*
     * 根据分类id查询菜品
     * */
    @Override
    public List<Dish> selectByListId(Long categoryId) {

        Dish dish=Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.selectByDishId(dish);
    }
}








